﻿#define Test

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TextExtract
{
    public partial class Form1 : Form
    {
        public Form1 () {
            InitializeComponent();
        }

        private void PathBox_KeyDown (object sender, KeyEventArgs e) {
            if (e.KeyCode == Keys.Enter) FindBtn_Click(sender, e);
        }
        private void PathSelectBtn_Click (object sender, EventArgs e) {
            FolderBrowserDialog fd = new FolderBrowserDialog();
            fd.ShowNewFolderButton = true;
            fd.RootFolder = Environment.SpecialFolder.Desktop;
            if (fd.ShowDialog() == DialogResult.OK) {
                PathBox.Text = fd.SelectedPath;
            }
        }

        private void FindBtn_Click (object sender, EventArgs e) {
            ResultComb.Items.Clear();
            if (string.IsNullOrEmpty(PathBox.Text) || string.IsNullOrEmpty(KeywordBox.Text)) return ;
            FindText(PathBox.Text, KeywordBox.Text);
            ResultComb.Items.Add(string.Format("共为您搜索到{0}项结果", ResultComb.Items.Count));
        }

        private void AddResult (string file, int line) {
            ResultComb.Items.Add(string.Format("{0}:{1}", file, line));
        }

        private void FindText (string path, string text) {
            foreach (string file in Directory.GetFiles(path)) {
                string[] line = File.ReadAllLines(file, Encoding.GetEncoding("GBK"));
                for (int i = 0; i < line.Length; i++) {
                    if (line[i].IndexOf(text) >= 0) {
                        AddResult(GetFileName(file), i + 1);
                    }
                }
            }

            foreach (string dir in Directory.GetDirectories(path)) {
                FindText(dir, text);
            }
        }

        private string GetFileName (string path) {
            int idx = path.LastIndexOf('\\') + 1;
            if (idx >= 0) return path.Substring(idx, path.Length - idx);
            return path;
        }
    }
}
